<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/27 0027
 * Time: 18:03
 */

namespace console\controllers;

use common\models\PercentageItem\PercentageItem;
use yii\console\Controller;

class PercentageController extends Controller
{
    /**
     * php yii percentage/index
     */
    public function actionIndex()
    {
        $percentageItem = PercentageItem::find()->where("parent_agent>0");

        foreach ( $percentageItem->each() as $item ) {
            $pItem = PercentageItem::findOne([
                "plug_id" => $item->plug_id,
                "created_date" => $item->created_date,
                "manager_id" => $item->manager_id,
                "agent_id" => $item->parent_agent,
            ]);
            if ( $pItem ) {
                continue;
            }
            $pItem = new PercentageItem();
            $pItem->attributes = $item->attributes;
            $pItem->agent_id = $item->parent_agent;

            $ret = PercentageItem::find()->select(["sum(real_num) as real_num", "sum(upper_num) as upper_num"])->where([
                "plug_id" => $item->plug_id,
                "created_date" => $item->created_date,
                "manager_id" => $item->manager_id,
                "parent_agent" => $item->parent_agent,
            ])->asArray()->one();
            $pItem->real_num = $ret["real_num"];
            $pItem->upper_num = $ret["upper_num"];
            $pItem->self_real_num = 0;
            $pItem->self_upper_num = 0;
            $pItem->parent_agent = 0;
            if ( $pItem->insert() ) {
                $this->stdout("OK【agent $pItem->agent_id 】real_num： $pItem->real_num ，upper_num： $pItem->upper_num  \r\n");
            } else {
                $this->stdout("fail【agent $pItem->agent_id 】\r\n");
            }
        }
    }

    public function actionT()
    {
        $percentageItem = PercentageItem::find()->where("parent_agent=agent_id");
        foreach ( $percentageItem->each() as $item ) {
            $item->parent_agent = 0;
            $item->self_real_num = 0;
            $item->self_upper_num = 0;
            if ( $item->update(0) ) {
                $this->stdout("OK【agent $item->agent_id 】real_num： $item->real_num ，upper_num： $item->upper_num ，date： $item->created_date  \r\n");
            } else {
                $this->stdout("fail【agent $item->agent_id 】\r\n");
            }
        }
    }
}